package cn.iocoder.yudao.module.tms.service.orderfollowlog;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.tms.controller.admin.order.vo.OrderSaveReqVO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.tms.controller.admin.orderfollowlog.vo.*;
import cn.iocoder.yudao.module.tms.dal.dataobject.orderfollowlog.OrderFollowLogDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.tms.dal.mysql.orderfollowlog.OrderFollowLogMapper;
import cn.iocoder.yudao.module.tms.dal.dataobject.orderfollowlog.OrderFollowLogAttachmentDO;
import cn.iocoder.yudao.module.tms.service.order.OrderService;
import cn.iocoder.yudao.module.tms.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.tms.enums.ClearanceStatusEnum;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.tms.enums.ErrorCodeConstants.*;

/**
 * 订单跟进日志 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrderFollowLogServiceImpl implements OrderFollowLogService {

    @Resource
    private OrderFollowLogMapper orderFollowLogMapper;
    
    @Resource
    private OrderFollowLogAttachmentService orderFollowLogAttachmentService;
    
    @Resource
    private OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrderFollowLog(OrderFollowLogSaveReqVO createReqVO) {
        // 插入
        OrderFollowLogDO orderFollowLog = BeanUtils.toBean(createReqVO, OrderFollowLogDO.class);
        orderFollowLogMapper.insert(orderFollowLog);
        
        // 保存附件
        saveFollowLogAttachments(orderFollowLog.getId(), createReqVO.getAttachments());
        
        // 同步更新产品信息的处理状态
        if (createReqVO.getProcessStatus() != null) {
            OrderDO order = orderService.getOrder(createReqVO.getOrderId());
            if (order != null) {
                // 先获取完整的产品信息
                OrderSaveReqVO updateReqVO = BeanUtils.toBean(order, OrderSaveReqVO.class);
                // 更新处理状态
                updateReqVO.setProcessStatus(createReqVO.getProcessStatus().getCode());
                orderService.updateOrder(updateReqVO);
            }
        }

        // 返回
        return orderFollowLog.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderFollowLog(OrderFollowLogSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderFollowLogExists(updateReqVO.getId());
        // 更新
        OrderFollowLogDO updateObj = BeanUtils.toBean(updateReqVO, OrderFollowLogDO.class);
        orderFollowLogMapper.updateById(updateObj);
        
        // 更新附件
        saveFollowLogAttachments(updateReqVO.getId(), updateReqVO.getAttachments());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderFollowLog(Long id) {
        // 校验存在
        validateOrderFollowLogExists(id);
        // 删除附件
        orderFollowLogAttachmentService.deleteAttachmentsByFollowLogId(id);
        // 删除
        orderFollowLogMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderFollowLogListByIds(List<Long> ids) {
        // 删除附件
        for (Long id : ids) {
            orderFollowLogAttachmentService.deleteAttachmentsByFollowLogId(id);
        }
        // 删除
        orderFollowLogMapper.deleteByIds(ids);
    }

    private void validateOrderFollowLogExists(Long id) {
        if (orderFollowLogMapper.selectById(id) == null) {
            throw exception(ORDER_FOLLOW_LOG_NOT_EXISTS);
        }
    }

    @Override
    public OrderFollowLogDO getOrderFollowLog(Long id) {
        return orderFollowLogMapper.selectById(id);
    }

    @Override
    public PageResult<OrderFollowLogDO> getOrderFollowLogPage(OrderFollowLogPageReqVO pageReqVO) {
        return orderFollowLogMapper.selectPage(pageReqVO);
    }
    
    /**
     * 保存跟进记录附件
     *
     * @param followLogId 跟进记录ID
     * @param attachmentVOs 附件信息列表
     */
    private void saveFollowLogAttachments(Long followLogId, List<String> attachmentVOs) {
        List<OrderFollowLogAttachmentDO> attachments = new ArrayList<>();
        if (CollUtil.isNotEmpty(attachmentVOs)) {
            for (int i = 0; i < attachmentVOs.size(); i++) {

                String attachment = attachmentVOs.get(i);
                if (attachment == null) {
                    continue;
                }
                //String attachmentName = 去掉路径和后缀
                String attachmentName = attachment.substring(attachment.lastIndexOf("/") + 1, attachment.lastIndexOf("."));
                String attachmentType = attachment.substring(attachment.lastIndexOf(".") + 1);

                OrderFollowLogAttachmentDO attachmentDO = OrderFollowLogAttachmentDO.builder()
                        .attachmentName(attachmentName)
                        .attachmentUrl(attachment)
                        .attachmentType(attachmentType)
                        .sort(i)
                        .build();
                attachments.add(attachmentDO);
            }
        }
        orderFollowLogAttachmentService.saveFollowLogAttachments(followLogId, attachments);
    }
}